﻿using IDAL;
using MODEL;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    //侯海啸
    public class BaseDAL<T> : IBaseDAL<T> where T : BaseModel, new()
    {
        public ShopEntities entities = DBContextFactory.GetEntities();
        //添加
        public virtual void Add(T model)
        {
            DbEntityEntry entityEntry = entities.Entry<T>(model);
            entityEntry.State = EntityState.Added;

        }
        //根据id删除
        public virtual void Delete(int id)
        {
            T model = new T()
            {
                ID = id
            };
            DbEntityEntry entityentry = entities.Entry<T>(model);
            entityentry.State = EntityState.Deleted;

        }
        //根据类删除
        public virtual void Delete(T model)
        {
            DbEntityEntry entityEntry = entities.Entry(model);
            entityEntry.State = EntityState.Deleted;

        }
        //获取所有
        public virtual List<T> GetAll()
        {
            return entities.Set<T>().ToList();
        }
        //获取单个
        public virtual T GetOne(int id)
        {
            return entities.Set<T>().First(x => x.ID == id);
        }
        //更新
        public virtual void Update(T model)
        {
            DbEntityEntry entityEntry = entities.Entry<T>(model);
            entityEntry.State = EntityState.Modified;


        }
        public int SaveChange()
        {
            return entities.SaveChanges();
        }

        public virtual List<T> Search(Func<T, bool> where)
        {
            return entities.Set<T>().Where(where).ToList();
        }

        public virtual List<T> Search(int pageSize, int pageIndex, bool isDesc, Func<T, bool> where)
        {
            //侯海啸
            //分页
            if (isDesc)
            {
                return entities.Set<T>().Where(where).OrderByDescending(x => x.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                return entities.Set<T>().Where(where).OrderBy(x => x.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            }
        }

        public virtual int GetCount(Func<T, bool> where)
        {
            return entities.Set<T>().Where(where).Count();
        }
        public DbContextTransaction BeginTran()
        {
            var tran = entities.Database.BeginTransaction();
            return tran;

        }
    }
}